<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class TaskClass extends Model
{
    //
    protected $table = 'task_class';
    protected $guarded = [];
    public $timestamps = false;

    public function getClassTemplate($count){
        $list = Db::table('task_class as tc')
            ->select('tc.*','t.name')
            ->leftJoin('tasks as t','tc.task_id','=','t.Id')
            ->orderBy('tc.id', 'desc')
            ->paginate($count);
        return $list;

    }

    public function saveTaskClass($params)
    {
        try {
            if (isset($params['title']) && !empty($params['title'])) {
                $taskClassMdl = db::table('task_class')
                    ->where('title', $params['title']);
                if (isset($params['id']) && !empty($params)) {
                    $taskClassMdl = $taskClassMdl->where('id', '<>', $params['id']);
                }
                $taskClassMdl = $taskClassMdl->first();
                if (!empty($taskClassMdl)) {
                    throw new \Exception('该分类名称已存在，不可重复命名！');
                }
            } else {
                throw new \Exception('请填写分类名称！');
            }

//            if (!isset($params['fid']) || empty($params['fid'])){
//                $params['fid'] = 0;
//                $params['level'] = 1;
//            }else{
//                $params['level'] = 2;
//            }
            if (!isset($params['fid'])){
                throw new \Exception('未给定上级分类标识！');
            }else{
                if (!empty($params['fid'])){
                    $info = db::table('task_class')->where('id', $params)->first();
                    if (empty($info)){
                        throw new \Exception('未查询到上级分类数据！');
                    }
                    $params['level'] = $info->level+1;
                }else{
                    $params['level'] = 1;
                }
            }

            if (isset($params['id']) && !empty($params['id'])) {
                $taskClassMdl = db::table('task_class')->where('id', $params['id'])->first();
                if (empty($taskClassMdl)) {
                    throw new \Exception('分类数据不存在！');
                }
                if (isset($params['level'])) {
                    if ($taskClassMdl->level != $params['level']) {
                        throw new \Exception('不允许更改分类等级！');
                    }
                }
            }

            if (isset($params['ext']) && !empty($params['ext'])) {
                if ($params['level'] != 3) {
                    throw new \Exception('父级分类不可增加模块！');
                }
                foreach ($params['ext'] as $item) {
                    if (!isset($item['name'])) {
                        throw new \Exception('请填写模块字段！');
                    }
                    if (!preg_match("/^[a-zA-Z_\s]+$/", $item['name'])) {
                        throw new \Exception('模块字段只能英文格式和下划线！');
                    }

                    if (!isset($item['label'])) {
                        throw new \Exception('请填写模块名称！');
                    }
                    if (!isset($item['type'])) {
                        throw new \Exception('请选择模块类型！');
                    }
                    if (isset($item['api'])) {
                        if (!isset($item['api_id'])) {
                            throw new \Exception('api接口需要api_id！');
                        }
                        if (!isset($item['api_label'])) {
                            throw new \Exception('api接口需要api_label！');
                        }
                    }

                    if ($item['type'] == 2) {
                        if (!isset($item['api']) || $item['api'] == null || $item['api'] == '') {
                            throw new \Exception('下拉框需要api路径！');
                        }
                        if (!isset($item['api_id']) || $item['api_id'] == null || $item['api_id'] == '') {
                            throw new \Exception('下拉框需要api_id！');
                        }
                        if (!preg_match("/^[a-zA-Z_\s]+$/", $item['api_id'])) {
                            throw new \Exception('下拉框api_id只能英文格式和下划线！');
                        }
                        if (!isset($item['api_label']) || $item['api_label'] == null || $item['api_label'] == '') {
                            throw new \Exception('下拉框需要api_label！');
                        }
                        if (!preg_match("/^[a-zA-Z_\s]+$/", $item['api_label'])) {
                            throw new \Exception('下拉框api_label只能英文格式和下划线！');
                        }
                    }
                }
            }
            if (isset($params['id'])) {
                $id = $params['id'];
                $update = db::table('task_class')->where('id', $id)->update(
                    [
                        'title' => $params['title'],
                        'fid' => $params['fid'],
                        'level' => $params['level'],
                    ]
                );
                $delete = db::table('task_class')->where('class_id', $id)->delete();
            } else {
                $id = db::table('task_class')->insertGetId(
                    [
                        'title' => $params['title'],
                        'fid' => $params['fid'] ?? 0,
                        'level' => $params['level'] ?? 1,
                    ]
                );
            }
            if ($id > 0) {
                if (isset($params['ext']) && empty($params['ext'])) {
                    foreach ($params['ext'] as $item) {
                        $add = array();
                        $add['class_id'] = $id;
                        $add['name'] = $item['name'];
                        $add['label'] = $item['label'];
                        $add['type'] = $item['type'];
                        if (isset($item['api'])) {
                            $add['api'] = $item['api'];
                        }
                        if (isset($item['api_id'])) {
                            $add['api_id'] = $item['api_id'];
                        }
                        if (isset($item['api_label'])) {
                            $add['api_label'] = $item['api_label'];
                        }
                        if (isset($item['api_param'])) {
                            $add['api_param'] = $item['api_param'];
                        }
                        TaskClassModule::insertGetId($add);
                    }
                }
            } else {
                throw new \Exception('分类数据保存失败！');
            }

            return ['code' => 200, 'msg' => '保存成功！'];
        } catch (\Exception $e) {
            return ['code' => 500, 'msg' => '保存失败！原因：'.$e->getMessage().'；位置：'.$e->getLine()];
        }
    }

    public function getTaskClassList($params)
    {
        $list = db::table('task_class as a')
            ->leftJoin('tasks as b', 'a.task_id', '=', 'b.Id');

        if (isset($params['fid'])){
            $list = $list->where('a.fid', $params['fid']);
        }

        if (isset($params['level'])){
            $list = $list->where('a.level', $params['level']);
        }

        $list = $list->orderBy('id', 'DESC')
            ->get(['a.*', 'b.name as task_name']);
        $result = [];
        foreach ($list as $item){
            $item->task_name = $item->task_name ?? '';
            if ($item->level == 1){
                $result[] = $item;
            }
        }
        foreach ($result as $v){
            $child = [];
            foreach ($list as $item){
                if ($v->id == $item->fid){
                    $child[] = $item;
                }
            }
            $v->child = $child;
        }
        // 如果统计要全部数据的统计，则分页要放置最后
        $count = count($result);
        // 数组分页
        if (isset($params['limit']) && !empty($params['limit']) && isset($params['page']) && !empty($params['page'])){
            $offset = $params['limit'] * ($params['page'] - 1);
            $result = array_slice($result, $offset, $params['limit']);
        }else{
            $result = array_slice($result, 0, 30); // 默认第一页，显示30条
        }
        return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count, 'list' => $result]];
    }

    public function deleteTaskClass($params)
    {

    }
}
